package fr.curriculumvitae.anthony.stephan.utils;

import org.jsoup.Jsoup;

import fr.curriculumvitae.anthony.stephan.R;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Looper;

public class UpdateChecker extends AsyncTask<Void, Integer, Boolean> {
	
	private static final String TAG = "UpdateChecker";

	private static final int UPDATE_AVAILABLE = 1;
	private static final int UPDATE_LATEST = 0;
	private static final int UPDATE_NOK = -1;
	
	private Context context;
	private String packageStr;
	private boolean notifyProgress;
	private boolean notifyUpdate;
	private boolean notifyNoUpdate;
	private boolean notifyError;
	
	private AlertDialog dialog;
	
	public UpdateChecker(Context context, String packageStr, 
			boolean notifyProgress, boolean notifyUpdate, boolean notifyNoUpdate, boolean notifyError) {
		this.context = context;
		this.packageStr = packageStr;
		this.notifyProgress = notifyProgress;
		this.notifyUpdate = notifyUpdate;
		this.notifyNoUpdate = notifyNoUpdate;
		this.notifyError = notifyError;
		this.dialog = null;
	}
	
	@Override
	protected void onPreExecute() {
		if(notifyProgress) {
			dialog = new ProgressDialog(context);
			dialog.setCancelable(false);
			dialog.setTitle(context.getString(R.string.update_check_title));
			dialog.setMessage(context.getString(R.string.update_check_msg));
			dialog.show();
		}
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		if(notifyProgress && dialog != null) {
			dialog.cancel();
		}
	}
	
	@Override
	protected Boolean doInBackground(Void... arg0) {
		try{
			Looper.prepare();
			String curVersion = context.getPackageManager().getPackageInfo(packageStr, 0).versionName; 
			String newVersion = curVersion;
			newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + packageStr + "&hl=en")
					.timeout(30000)
					.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
					.referrer("http://www.google.com")
					.get()
					.select("div[itemprop=softwareVersion]")
					.first()
					.ownText();
			Log.i(TAG, "curVersion : " + curVersion+", newVersion : "+newVersion);
			boolean needUpdate = ((StringUtils.getLongFromString(curVersion) < StringUtils.getLongFromString((newVersion)) ? true : false));
			Log.i(TAG, "need update : " + needUpdate);
			if(needUpdate) {
				publishProgress(UPDATE_AVAILABLE);
			} else {
				publishProgress(UPDATE_LATEST);
			}
		} catch (Exception e) {
			Log.e(TAG, "Exception : ",e);
			publishProgress(UPDATE_NOK);
		}	
		return true;
	}
	
	@Override
	protected void onProgressUpdate(Integer... value) {
		switch(value[0]) {
		
		case UPDATE_AVAILABLE:
			if(notifyUpdate) {
				if(dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				dialog = new AlertDialog.Builder(context)
				.setTitle(R.string.update_available_title)
				.setMessage(R.string.update_available_msg)
				.setNegativeButton(android.R.string.no, null)
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String url = "https://play.google.com/store/apps/details?id=" + packageStr + "&hl=en";
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setData(Uri.parse(url));
						context.startActivity(i);
					}
				}).create();
				dialog.show();
			} 
			break;
			
		case UPDATE_LATEST:
			if(notifyNoUpdate) {
				if(dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				dialog = new AlertDialog.Builder(context)
				.setTitle(R.string.update_latest_title)
				.setMessage(R.string.update_latest_msg)
				.setPositiveButton(android.R.string.ok, null).create();
				dialog.show();
			}
			break;
			
		case UPDATE_NOK:
		default:
			if(notifyError) {
				if(dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				dialog = new AlertDialog.Builder(context)
				.setTitle(R.string.update_nok_title)
				.setMessage(R.string.update_nok_msg)
				.setPositiveButton(android.R.string.ok, null).create();
				dialog.show();
			}
			break;
		}
	}

}
